// import SearchBar from '../js/navbar/searchbar/searchbar.js';
import { createSlice } from '@reduxjs/toolkit';
import sessionRestore from '../sessionRestore'
import webviews from '../js/webviews.js';
import searchEngine from '../js/util/searchEngine.js';
function newTab(tab) {
  var newTab = {
    url: tab.url || '',
    title: tab.title || '',
    id: tab.id || Math.round(Math.random() * 100000000000000000),
    secure: tab.secure,   //todo
    private: tab.private || false, //todo
    readerable: tab.readerable || false, //todo
    scrollPosition: tab.scrollPosition || 0,
    muted: tab.muted || false, //todo
    hasAudio: false, //todo
    status:""
  };
  return newTab;
}
var initialState = {
  dark:true,
  star: true,
  hasAudio:false,
  muted:true,
  filled: false,
  pressed: true,
  star_hidden: false,
  block_hidden: false,
  block_opacity: 0.4,
  input_value: '', //end TabEditor
  tasks: [],
  tabs: [],
  show_drop: true,
  show_search: true,
  show_setting: false,
  tab_value: 0,
  goback_disabled: true,
  goforward_disabled: true,
  show_pwdview: false,
  show_task: false,
  show_pdf: false,
  pdf_data: null,
  show_error: false,
  show_download: false,
  show_find: false,
  show_book: false,
  show_capture: false,
  show_history: false,
  search_engine:"Bing",
  count: "",
  errs: []
};
const close_tab = (state) => {
  let itemIndex = state.tab_value;
  let tabid = state.tabs[itemIndex].id;
  if (state.tabs.length > 1) {//delete one tab
    const new_tabs = state.tabs.filter(
      (item, idx) => itemIndex !== idx
    );
    state.tabs = new_tabs;
    webviews.destroy(tabid);
    if (state.tab_value < state.tabs.length) {
    } else {
      state.tab_value = state.tabs.length - 1;
    }
    webviews.setSelected(state.tabs[state.tab_value].id, {
      focus: true,
    });
  } else {//to blank window
    state.tabs[state.tab_value].url = ""
    state.tabs[state.tab_value].title = ""
    webviews.openURL(state.tabs[state.tab_value].id, "");
  }
  state.show_search = false;
  // state.show_drop=false;
  if (state.tabs[state.tab_value]) state.input_value = state.tabs[state.tab_value].url;
}

export const partsSlice = createSlice({
  name: 'parts',
  initialState: initialState,
  reducers: {
    INIT_DATA: (state, action) => {
      console.log("INIT_TABS======================");
      for(one in action.payload)
      {
        state[one]=action.payload[one]
      }
      if (state.tabs.length == 0) {
        let url = 'file://' + myglobal['home'] + '/pages/index.html';
        // dispatch(store.partsSlice.actions.ADD_TAB({ url }))
        tab = newTab({url:url});
        state.tabs.push(tab)
        state.tab_value = state.tabs.length - 1;
      }
      let i = 0;
      for (i = 0; i < state.tabs.length; i++) {
        state.tabs[i].id = String(
          state.tabs[i].id || Math.round(Math.random() * 100000000000000000)
        );
        webviews.add(state.tabs[i]);
      }
      webviews.setSelected(state.tabs[state.tab_value].id, {
        focus: true,
      });
      if (state.tabs[state.tab_value]) state.input_value = state.tabs[state.tab_value].url;
    },
    SWITCH_TAB:(state, action) => {
      let at=action.payload;
      state.tab_value=at;
      webviews.setSelected(state.tabs[state.tab_value].id, {
        focus: true,
      });
      state.show_search=false;
      // state.show_drop=false;
      if(state.tabs[state.tab_value]) state.input_value=state.tabs[state.tab_value].url;
    },
    TAB_STATUS:(state, action) => {
      console.log("TAB_STATUS=======")
      console.log(action.payload)
      // let i=0;
      state.tabs[action.payload.index].status=action.payload.status
      // console.log(state)
    },
    CLOSE_TAB_ID:(state, action) => {
      let i=0;
      for(i=0;i<state.tabs.length;i++){
        if(state.tabs[i].id===action.payload){
          state.tab_value=i;
          close_tab(state)
          break;
        }
      }
    },
    CLOSE_TAB: (state, action) => {
      close_tab(state);
    },
    OPEN_URL: (state, action) => {
      let url = action.payload;
      state.show_search = false;
      state.show_book = false;
      state.show_history = false;
      state.tabs[state.tab_value].url = url;
      state.input_value=url;
      state.tabs[state.tab_value].title = "";
      state.show_error = false;
      webviews.openURL(state.tabs[state.tab_value].id, url);
    },
    DOWNLOAD:(state, action) => {
      let url=action.payload.url;
    },
    ADD_TAB: (state, action) => {
      /* new tabs can't be created in focus mode */
      data = action.payload;
      // addTab(window.tasklist.task.tabs.add({url: data.url || ''}));
      tab = newTab(data);
      state.tabs.push(tab)
      state.tab_value = state.tabs.length - 1;
      webviews.add(tab);
      console.log("addTab=========================")
      console.log(tab);
      webviews.setSelected(tab.id, {
        focus: true,
      });
      state.show_search = false;
      // state.show_drop=false;
      if (state.tabs[state.tab_value]) state.input_value = state.tabs[state.tab_value].url;
    },
    // INIT_TABS: (state, action) => {
    // },
    START_FIND: (state, action) => {
      state.show_drop = true;
      state.show_search = false;
      state.show_find = true;
    },
    HAS_AUDIO: (state, action) => {
      state.hasAudio=action.payload.hasAudio;
      tabid = action.payload.tabid;
      for (i = 0; i < state.tabs.length; i++) {
        if (state.tabs[i].id == tabid) {
          console.log("change hasAudio ")
          state.tabs[i].hasAudio = state.hasAudio
          if (state.tabs[i].hasAudio) {
            webviews.callAsync(tabid, 'setAudioMuted', state.muted)
            state.tabs[i].muted= state.muted
          }
          break
        }
      }
    },
    TOGGLE_MUTE: (state, action) => {
      state.muted=!state.muted
      let itemIndex = state.tab_value;
      let tab=state.tabs[itemIndex];
      let tabId = state.tabs[itemIndex].id;
      //todo
      if (tab.hasAudio) {
        webviews.callAsync(tabId, 'setAudioMuted', state.muted)
        tab.muted= state.muted
      }
    },
    SCROLL: (state, action) => {
      tabid = action.payload.tabid;
      for (i = 0; i < state.tabs.length; i++) {
        if (state.tabs[i].id == tabid) {
          state.tabs[i].scrollPosition = action.payload.pos;
          break
        }
      }
    },
    UPDATE_TASKS: (state, action) => {
      state.tasks = getTasks();
    },
    INPUT_CHANGE: (state, action) => {
      state.input_value = action.payload;
    },
    SHOW_CAPTURE: (state, action) => {
      state.show_capture = action.payload;
      if (state.show_capture) {
        state.show_drop = true;
      }
    },
    SHOW_PWDVIEW: (state, action) => {
      state.show_pwdview = action.payload;
      if (state.show_pwdview) {
        state.show_search = false;
        state.show_drop = true;
      }
    },
    SHOW_FIND: (state, action) => {
      state.show_find = action.payload;
      if (state.show_find) {
        state.show_drop = true;
      }
    },
    SHOW_DOWNLOAD: (state, action) => {
      state.show_download = action.payload;
      if (state.show_download) {
        state.show_search = false;
        state.show_drop = true;
      }
    },
    CLICK_STAR: (state, action) => {
      let isBookmarked = action.payload;
      if (isBookmarked) {
        state.star = false
        state.filled = true;
        state.pressed = true;
      } else {
        state.star = true
        state.filled = false;
        state.pressed = false;
      }
    },
    UPDATE_COUNT: (state, action) => {
      state.count = action.payload;
    },
    GOBACK_DISABLE: (state, action) => {
      state.goback_disabled = action.payload;
    },
    NAVIGATE: (state, action) => {
      tabid = action.payload.tabid;
      url = action.payload.url;
      for (i = 0; i < state.tabs.length; i++) {
        if (state.tabs[i].id == tabid) {
          state.tabs[i].url = url;
        }
      }
    },
    TITLE: (state, action) => {
      tabid = action.payload.tabid;
      title = action.payload.title;
      for (i = 0; i < state.tabs.length; i++) {
        if (state.tabs[i].id == tabid) {
          state.tabs[i].title =title;
          break
        }
      }
    },
    GOFORWARD_DISABLE: (state, action) => {
      state.goforward_disabled = action.payload;
    },
    TAB_VALUE: (state, action) => {
      state.tab_value = action.payload;
    },
    SHOW_DROP: (state, action) => {
      state.show_drop = action.payload;
    },
    SEARCH_ENGINE: (state, action) => {
      searchEngine.changeTo(action.payload)
      state.search_engine = action.payload;
    },
    TOGGLE_DARK: (state, action) => {
      state.dark = !state.dark;
    },
    TOGGLE_DROP: (state, action) => {
      state.show_drop = !state.show_drop;
    },
    TOGGLE_SEARCH: (state, action) => {
      state.show_search = !state.show_search
    },
    TOGGLE_TASK: (state, action) => {
      state.show_task = !state.show_task
      if (state.show_task) { state.show_drop = true }
    },
    SHOW_SEARCH: (state, action) => {
      state.show_search = action.payload;
    },
    SHOW_PDF: (state, action) => {
      state.show_pdf = action.payload;
      if (state.show_pdf) { state.show_drop = true }
    },
    SHOW_ERROR: (state, action) => {
      state.show_error = action.payload;
      if (state.show_error) { state.show_drop = true }
    },
    ERROR: (state, action) => {
      console.log("error-----------------------");
      console.log(action.payload)
      state.errs.unshift(action.payload)
      while((state.errs.length)>5){
        state.errs.pop();
      }
      let err_url=action.payload.validatedURL.toLowerCase()
      let now_url=state.tabs[state.tab_value].url.toLowerCase()
      if(err_url==now_url && action.payload.isMainFrame){
        state.show_error = true;
        state.show_drop = true;
      }
    },
    SHOW_BOOK: (state, action) => {
      state.show_book = action.payload
      if (state.show_book) {
        state.show_history = false;
        state.show_drop = true;
        state.show_search = false;
      }
    },
    SHOW_SETTING: (state, action) => {
      state.show_drop = true;
      state.show_setting = action.payload;
    },
    SHOW_HISTORY: (state, action) => {
      state.show_drop = true;
      state.show_history = action.payload;
    },
    SAVE: (state, action) => {
      sessionRestore.save(state);
    },
  },
});
export const actions = partsSlice.actions;
export const sessionRestoreAction = (data) => (dispatch) => {
  sessionRestore.restore(dispatch);
};
export default partsSlice.reducer;
